<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <script>
    //  使用场景： 
    /* 
      1. 撤销功能
    */

    // 备忘对象
    class Memento {
      constructor(content) {
        this.content = content;
      }
      getContent() {
        return this.content;
      }
    }

    // 备忘列表
    class CareTaker {
      constructor() {
        this.list = [];
      }
      add(memento) {
        this.list.push(memento);
      }
      get(index) {
        return this.list[index];
      }
    }

    // 编辑器
    class Editor {
      constructor() {
        this.content = null;
      }
      setContent(content) {
        this.content = content;
      }
      getContent() {
        return this.content;
      }
      saveContentToMemento() {
        return new Memento(this.content);
      }
      getContentFormMenmento(memento) {
        this.content = memento.getContent();
      }
    }

    // 测试代码
    const editor = new Editor()
    const careTaker = new CareTaker();
    editor.setContent('111');
    editor.setContent('222');
    careTaker.add(editor.saveContentToMemento()); // 保存到备忘录
    editor.setContent('333');
    careTaker.add(editor.saveContentToMemento()); // 保存到备忘录
    editor.setContent('444');

    console.log(editor.getContent());
    editor.getContentFormMenmento(careTaker.get(1)) // 撤销
    console.log(editor.getContent());
    editor.getContentFormMenmento(careTaker.get(0)) // 撤销
    console.log(editor.getContent());
  </script>
</body>

</html>